#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
用于处理【资产负债表】逻辑  BalanceSheet
'''



from datetime import datetime

from PyQt5.uic.properties import QtCore
from dateutil.relativedelta import relativedelta


from PyQt5.QtWidgets import QWidget, QAbstractItemView, QTableWidgetItem
from PyQt5 import QtWidgets
from xToolkit.xstring import xstring

import init
import initBalanceSheetPage


import toolkit
from AccountBook import AccountBook
from BalanceSheet import BalanceSheet
from BalanceSheetDetailDialog import BalanceSheetDetailDialog

from initLogger import logger

from ui.BalanceSheetUI_relative_layout import Ui_BalanceSheet


class BalanceSheetWidget(QWidget, Ui_BalanceSheet):
    def __init__(self):
        super(BalanceSheetWidget, self).__init__()
        self.setupUi(self)

        self.currentDate = datetime.now()  #记录当前事件
        self.targetDate = self.currentDate - relativedelta(days=init.GO_DAYS)#记录当前系统查看数据的时间

        self.initBalanceSheet()


    def initBalanceSheet(self):
        '''
        函数功能：初始化资产负债表页面
        :return:
        '''
        logger.debug("call initBalanceSheet")

        self.initBalanceSheetUI()
       # self.initBalanceSheetTableUI()
        self.initBalanceSheetPropertyTableUI()
        self.initBalanceSheetOwnershipTableUI()

        self.initBalanceSheetPropertyTableData()  #对资产负债表数据进行初始化
        self.initBalanceSheetOwnershipTableData()

    def initBalanceSheetTitleUI(self):
        balanceSheetTitleStr="%d年%d月——资产负债表"%(self.targetDate.year, self.targetDate.month)
        self.title_label.setText(balanceSheetTitleStr)


    def initBalanceSheetUI(self):
        '''
        函数功能：初始化资产负债表的UI
        :return:
        '''
        # 初始化标题
        self.initBalanceSheetTitleUI()

        #初始化查询模块相关控件
        self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.month_comboBox.addItems(init.MONTH_NAME_LIST)
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

    def initBalanceSheetPropertyTableUI(self):
        '''
        函数功能：初始化资产负债资产表
        :return:
        '''
        self.balance_sheet_property_tableWidget.setRowCount(initBalanceSheetPage.BALANCE_SHEET_ROW_COUNT)  # 设置行数目
        self.balance_sheet_property_tableWidget.setColumnCount(initBalanceSheetPage.BALANCE_SHEET_COLUMN_COUNT)  # 设置列数目
        self.balance_sheet_property_tableWidget.setHorizontalHeaderLabels(initBalanceSheetPage.BALANCE_SHEET_COLUMN_CONTEXT)

        self.balance_sheet_property_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.balance_sheet_property_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.balance_sheet_property_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.balance_sheet_property_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.balance_sheet_property_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.balance_sheet_property_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.balance_sheet_property_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.balance_sheet_property_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

    def initBalanceSheetOwnershipTableUI(self):
        '''
        函数功能：初始化资产负债权属表UI
        :return:
        '''
        self.balance_sheet_ownership_tableWidget.setRowCount(initBalanceSheetPage.BALANCE_SHEET_ROW_COUNT)  # 设置行数目
        self.balance_sheet_ownership_tableWidget.setColumnCount(initBalanceSheetPage.BALANCE_SHEET_COLUMN_COUNT)  # 设置列数目
        self.balance_sheet_ownership_tableWidget.setHorizontalHeaderLabels(initBalanceSheetPage.BALANCE_SHEET_COLUMN_CONTEXT)

        self.balance_sheet_ownership_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.balance_sheet_ownership_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.balance_sheet_ownership_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.balance_sheet_ownership_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.balance_sheet_ownership_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.balance_sheet_ownership_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.balance_sheet_ownership_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.balance_sheet_ownership_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

    def initBalanceSheetPropertyTableData(self):
        '''
        函数功能：初始化资产负债表数据
        :return:
        '''

        balanceSheet = BalanceSheet(self.targetDate.year, self.targetDate.month,)
        balanceSheetResult = balanceSheet.getBalanceSheetDataMonthly(init.TYPE_PROPERTY)

        balanceSheetLen = len(balanceSheetResult) + 1
        self.balance_sheet_property_tableWidget.setRowCount(balanceSheetLen)

        differenceValue = 0.0
        startTotalValue = 0.0
        endTotalValue = 0.0
        differenceTotalValue = 0.0

        for i in range(len(balanceSheetResult)):
            dataRow = balanceSheetResult[i]

            subjectPathName = "%s\t" % (dataRow.path)
            subjectPathWidgetItem = QTableWidgetItem(subjectPathName)
            self.balance_sheet_property_tableWidget.setItem(i, 0, subjectPathWidgetItem)

            categoryName = "%s\t" % (dataRow.category)
            catrgeoyWidgetItem = QTableWidgetItem(categoryName)
            self.balance_sheet_property_tableWidget.setItem(i, 1, catrgeoyWidgetItem)


            startValueStr=xstring.dispose(toolkit.processValueSignificant(dataRow.start_value)).humanized_amount(complex=True)
            startTotalValue = startTotalValue + dataRow.start_value
            startValueWidgetItem = QTableWidgetItem(startValueStr)
            self.balance_sheet_property_tableWidget.setItem(i, 2, startValueWidgetItem)

            endValueStr=xstring.dispose(toolkit.processValueSignificant(dataRow.end_value)).humanized_amount(complex=True)
            endTotalValue = endTotalValue + dataRow.end_value
            endValueWidgetItem = QTableWidgetItem(endValueStr)
            self.balance_sheet_property_tableWidget.setItem(i, 3, endValueWidgetItem)

            differenceValue = dataRow.end_value - dataRow.start_value
            differenceValueStr=xstring.dispose(toolkit.processValueSignificant(differenceValue)).humanized_amount(complex=True)
            differenceValueWidgetItem = QTableWidgetItem(differenceValueStr)
            self.balance_sheet_property_tableWidget.setItem(i, 4, differenceValueWidgetItem)

        # 展示合计数据
        subjectPathName = "%s\t" % (initBalanceSheetPage.PROPERTY_TOTAL_STR)
        subjectPathWidgetItem = QTableWidgetItem(subjectPathName)
        self.balance_sheet_property_tableWidget.setItem(balanceSheetLen-1, 0, subjectPathWidgetItem)
        self.balance_sheet_property_tableWidget.setItem(balanceSheetLen-1, 1, subjectPathWidgetItem)


        startValueStr=xstring.dispose(toolkit.processValueSignificant(startTotalValue)).humanized_amount(complex=True)
        startValueWidgetItem = QTableWidgetItem(startValueStr)
        self.balance_sheet_property_tableWidget.setItem(balanceSheetLen-1, 2, startValueWidgetItem)

        endValueStr=xstring.dispose(toolkit.processValueSignificant(endTotalValue)).humanized_amount(complex=True)
        endValueWidgetItem = QTableWidgetItem(endValueStr)
        self.balance_sheet_property_tableWidget.setItem(balanceSheetLen-1, 3, endValueWidgetItem)

        differenceTotalValue = endTotalValue - startTotalValue
        differenceTotalValueStr = xstring.dispose(toolkit.processValueSignificant(differenceTotalValue)).humanized_amount(complex=True)
        differenceTotalValueWidgetItem = QTableWidgetItem(differenceTotalValueStr)
        self.balance_sheet_property_tableWidget.setItem(balanceSheetLen - 1, 4, differenceTotalValueWidgetItem)

        self.balance_sheet_property_tableWidget.resizeRowsToContents()
        self.balance_sheet_property_tableWidget.resizeColumnsToContents()

    def initBalanceSheetOwnershipTableData(self ):
        '''
        函数功能：初始化资产负债表数据
        :return:
        '''

        balanceSheet = BalanceSheet(self.targetDate.year, self.targetDate.month)
        balanceSheetResult = balanceSheet.getBalanceSheetDataMonthly(init.TYPE_OWNERSHIP)

        balanceSheetlen = len(balanceSheetResult) + 2
        self.balance_sheet_ownership_tableWidget.setRowCount(balanceSheetlen)


        startTotalValue = 0.0
        endTotalValue = 0.0
        differenceValue = 0.0
        differenceTotalValue = 0.0


        for i in range(len(balanceSheetResult)):
            dataRow = balanceSheetResult[i]

            subjectPathName = "%s\t" % (dataRow.path)
            sebjectPathWidgetItem = QTableWidgetItem(subjectPathName)
            self.balance_sheet_ownership_tableWidget.setItem(i, 0, sebjectPathWidgetItem)

            categoryName = "%s\t" % (dataRow.category)
            catrgeoyWidgetItem = QTableWidgetItem(categoryName)
            self.balance_sheet_ownership_tableWidget.setItem(i, 1, catrgeoyWidgetItem)


            startValueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.start_value)).humanized_amount(complex=True)
            startTotalValue = startTotalValue + dataRow.start_value
            startValueWidgetItem = QTableWidgetItem(startValueStr)
            self.balance_sheet_ownership_tableWidget.setItem(i, 2, startValueWidgetItem)


            endValueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.end_value)).humanized_amount(complex=True)
            endTotalValue = endTotalValue + dataRow.end_value
            endValueWidgetItem = QTableWidgetItem(endValueStr)
            self.balance_sheet_ownership_tableWidget.setItem(i, 3, endValueWidgetItem)

            differenceValue = dataRow.end_value - dataRow.start_value
            differenceValueStr=xstring.dispose(toolkit.processValueSignificant(differenceValue)).humanized_amount(complex=True)
            differenceValueWidgetItem = QTableWidgetItem(differenceValueStr)
            self.balance_sheet_ownership_tableWidget.setItem(i, 4, differenceValueWidgetItem)


        # 展示合计数据
        subjectPathName = "%s\t" % (initBalanceSheetPage.OWNERSHIP_TOTAL_STR)
        sebjectPathWidgetItem = QTableWidgetItem(subjectPathName)
        self.balance_sheet_ownership_tableWidget.setItem(balanceSheetlen-2, 0, sebjectPathWidgetItem)
        self.balance_sheet_ownership_tableWidget.setItem(balanceSheetlen-2, 1, sebjectPathWidgetItem)

        startValueStr = xstring.dispose(toolkit.processValueSignificant(startTotalValue)).humanized_amount(complex=True)
        startValueWidgetItem = QTableWidgetItem(startValueStr)
        self.balance_sheet_ownership_tableWidget.setItem(balanceSheetlen-2, 2, startValueWidgetItem)

        endValueStr = xstring.dispose(toolkit.processValueSignificant(endTotalValue)).humanized_amount(complex=True)
        endValueWidgetItem = QTableWidgetItem(endValueStr)
        self.balance_sheet_ownership_tableWidget.setItem(balanceSheetlen-2, 3, endValueWidgetItem)

        differenceTotalValue = endTotalValue - startTotalValue
        differenceTotalValueStr = xstring.dispose(toolkit.processValueSignificant(differenceTotalValue)).humanized_amount(complex=True)
        differenceTotalValueWidgetItem = QTableWidgetItem(differenceTotalValueStr)
        self.balance_sheet_ownership_tableWidget.setItem(balanceSheetlen-2, 4, differenceTotalValueWidgetItem)

        self.balance_sheet_ownership_tableWidget.resizeRowsToContents()
        self.balance_sheet_ownership_tableWidget.resizeColumnsToContents()



    def clearBalanceSheetTableContext(self):
        '''
        函数功能：清空资产负债表信息
        :return:
        '''

        self.balance_sheet_ownership_tableWidget.clear()
        self.balance_sheet_ownership_tableWidget.clear()


    def onSearch(self):
        '''
        函数功能：处理查询响应函数
        :return:
        '''

        year = int(self.year_comboBox.currentText())
        month = int(self.month_comboBox.currentText())
        self.targetDate = toolkit.setTargetDate(year, month)

        self.clearBalanceSheetTableContext()

        self.initBalanceSheetTitleUI()


        self.initBalanceSheetPropertyTableUI()
        self.initBalanceSheetPropertyTableData()

        self.initBalanceSheetOwnershipTableUI()
        self.initBalanceSheetOwnershipTableData()

    def onGoLastMonth(self):
        """
        函数功能；展示上一个月的资产负债表数据
        :return:
        """

        self.targetDate = toolkit.getLastMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.clearBalanceSheetTableContext()

        self.initBalanceSheetTitleUI()


        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initBalanceSheetPropertyTableUI()
        self.initBalanceSheetPropertyTableData()

        self.initBalanceSheetOwnershipTableUI()
        self.initBalanceSheetOwnershipTableData()

    def onGoNextMonth(self):
        """
        函数功能；展示下一个月的资产负债表数据
        :return:
        """

        self.targetDate = toolkit.getNextMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))

        self.clearBalanceSheetTableContext()

        self.initBalanceSheetTitleUI()


        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initBalanceSheetPropertyTableUI()
        self.initBalanceSheetPropertyTableData()

        self.initBalanceSheetOwnershipTableUI()
        self.initBalanceSheetOwnershipTableData()



    def onUpdateBalanceSheet(self):
        '''
        函数功能：更新记账簿数据
        :return:
        '''

        blanceSheet = BalanceSheet(self.targetDate.year, self.targetDate.month)
        blanceSheet.genBalanceSheet()

        self.clearBalanceSheetTableContext()

        self.initBalanceSheetTitleUI()


        self.initBalanceSheetPropertyTableUI()
        self.initBalanceSheetPropertyTableData()

        self.initBalanceSheetOwnershipTableUI()
        self.initBalanceSheetOwnershipTableData()


    def onUpdateAllYearBalanceSheet(self):
        '''
        函数功能：更新全年记账簿数据
        :return:
        '''
        pass


    def onPropertyTableDoubleClicked(self):
        '''
        函数功能：资产负债表资产表双击事件响应函数
        :return:
        '''

        selectRow = self.balance_sheet_property_tableWidget.selectedItems()[0].row()
        selectText = self.balance_sheet_property_tableWidget.selectedItems()[0].text().strip('\t')


        balanceSheetDetailDialog = BalanceSheetDetailDialog(parent=self,
                                                            selectRow=selectRow,
                                                            selectText=selectText,
                                                            year=self.targetDate.year,
                                                            month=self.targetDate.month)
        #balanceSheetDetailDialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)
        if balanceSheetDetailDialog.exec_():
            pass
        balanceSheetDetailDialog.destroy()

    def onOwnershipTableDoubleClicked(self):
        '''
        函数功能：资产负债表权属表双击事件响应函数
        :return:
        '''

        selectRow = self.balance_sheet_ownership_tableWidget.selectedItems()[0].row()
        selectText = self.balance_sheet_ownership_tableWidget.selectedItems()[0].text().strip('\t')


        balanceSheetDetailDialog = BalanceSheetDetailDialog(parent=self,
                                                            selectRow=selectRow,
                                                            selectText=selectText,
                                                            year=self.targetDate.year,
                                                            month=self.targetDate.month)

        #balanceSheetDetailDialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)

        if balanceSheetDetailDialog.exec_():
            pass
        balanceSheetDetailDialog.destroy()